package drds.plus.parser.parser.dml.add;

import drds.plus.parser.abstract_syntax_tree.expression.Expression;
import drds.plus.parser.abstract_syntax_tree.expression.primary.misc.RowValues;
import drds.plus.parser.lexer.Lexer;
import drds.plus.parser.lexer.Token;
import drds.plus.parser.parser.ExpressionParser;
import drds.plus.parser.parser.dml.DmlParser;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;


public abstract class InsertReplaceParser extends DmlParser {

    public InsertReplaceParser(Lexer lexer, ExpressionParser expressionParser) {
        super(lexer, expressionParser);
    }

    protected List<RowValues> rowDataList() {
        List<RowValues> valuesList = new LinkedList<RowValues>();
        List<Expression> rowValueList = rowValueList();
        valuesList.add(new RowValues(rowValueList));
        if (lexer.token() == Token.PUNC_COMMA) {
            while (lexer.token() == Token.PUNC_COMMA) {
                lexer.nextToken();
                rowValueList = rowValueList();//with nextToken()
                valuesList.add(new RowValues(rowValueList));
            }
        }
        valuesList = new ArrayList<RowValues>(valuesList);
        return valuesList;
    }

    /**
     * first token is <code>(</code>
     */
    private List<Expression> rowValueList() {
        match(Token.PUNC_LEFT_PAREN);
        if (lexer.token() == Token.PUNC_RIGHT_PAREN) {
            return Collections.emptyList();
        }
        lexer.nextToken();
        Expression expression = expressionParser.expression();
        //
        List<Expression> expressionList = new LinkedList<Expression>();
        expressionList.add(expression);
        if (lexer.token() == Token.PUNC_COMMA) {
            while (lexer.token() == Token.PUNC_COMMA) {
                lexer.nextToken();
                expression = expressionParser.expression();
                expressionList.add(expression);
            }//end lexer.nextToken(); is PUNC_RIGHT_PAREN
        }
        match(Token.PUNC_RIGHT_PAREN);//
        expressionList = new ArrayList<Expression>(expressionList);
        lexer.nextToken();//end
        return expressionList;
    }
}
